package secondBrush.string;

public class E04Leetcode151 {
    public String reverseWords(String s) {
        StringBuilder stringBuilder = removeSpace(s);
        String string = stringBuilder.toString();

        String[] worlds = string.split(" ");
        int length = worlds.length;
        String result = "";
        StringBuilder str = new StringBuilder();
        for (int i = length - 1; i >= 0; i--) {
            if (i == 0) {
                str.append(worlds[i]);
            } else {

                str.append(worlds[i] + " ");
            }
        }



        result = str.toString();

        return result;


    }

    private StringBuilder removeSpace(String s) {
        StringBuilder result = new StringBuilder();
        int start = 0;
        int end = s.length() - 1;
        while (s.charAt(start) == ' ') start++;
        while (s.charAt(end) == ' ') end--;
        while (start <= end) {
            char c = s.charAt(start);
            if (c != ' ' || result.charAt(result.length() - 1) != ' ') {
                result.append(c);
            }

            start++;

        }

        return result;


    }

    public static void main(String[] args) {
        String s = " hello world ";
        E04Leetcode151 e04Leetcode151 = new E04Leetcode151();
        System.out.println(e04Leetcode151.reverseWords(s));


    }
}
